package org.ring.rpc;

import org.ring.common.URL;
import org.ring.common.utils.reflect.ReflectUtils;

/**
 * @since 2024-10-28 19:33
 */
public class ConsumerConfig<T> {

    private static Protocol protocol = new DefaultProtocol();

    private static ProxyFactory proxyFactory = new JDKProxyFactory();

    private String interfaceName;

    private Class<?> interfaceClass;

    private String url;

    private transient volatile T ref;

    public void setInterfaceName(String interfaceName) {
        this.interfaceName = interfaceName;
        this.interfaceClass = ReflectUtils.forName(interfaceName, ConsumerConfig.class.getClassLoader());
    }

    public T get() {
        if (ref == null) {
            init();
        }

        return ref;
    }

    private synchronized void init()  {

        URL url = URL.valueOf(this.url);
        ServiceRepository.getInstance().registerService(interfaceClass);

        Invoker<T> invoker = protocol.refer(url);

        this.ref = proxyFactory.getProxy(invoker, new Class[] {interfaceClass});
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}
